//
//  SWPageUploader.swift
//  ChildStory
//
//  Created by linhan on 2017/1/23.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
class SWPageUploader: NSObject
{
    private var _pages:[SWPage] = []
    private let _queue:OperationQueue = OperationQueue()
    private var _orderID:String = ""
    
    private var _totalCount:Int = 0
    
    private var _record:SWOrderRecord
    
    init(record:SWOrderRecord)
    {
        _record = record
        super.init()
        
        _orderID = record.orderID ?? ""
        let pages:[SWPage] = record.pages?.flatMap({$0 as? SWPage}) ?? []
        _pages = pages
        _totalCount = pages.count
        let unuploadedPages:[SWPage] = record.unuploadedPages
        
        if unuploadedPages.count > 0
        {
            pause()
            
            for page in unuploadedPages
            {
                let localPath = SWPageManager.sharedManager().fetchStorePath(page, level: .origin)
                let task = SWUploadTask(page: page)
                task.origin = true
                task.localPath = localPath
                
                if let operation = SWUploadOperation(task: task)
                {
                    if !SWPageManager.sharedManager().productExists(page, level: .origin)
                    {
                        let generateTask = SWGenerationTask(page: page)
                        if let generateOperation = SWPageGenerateOperation(task: generateTask)
                        {
                            operation.addDependency(generateOperation)
                            SWPageManager.sharedManager().addOperation(generateOperation, priority: .veryHigh)
                        }
                    }
                    
                    //operation.successCallback = {[weak self] response in self?.uploadSuccess(response)}
                    
                    operation.successCallback = {[weak self] response in
                        //print("operation.successCallback")
                        self?.uploadSuccess(response)
                    }
                    
                    _queue.addOperation(operation)
                }
            }
            print("开始上传任务:", _queue.operations.count)
        }
        else
        {
            uploadAllComplete()
        }
        
    }
    
    var running:Bool{
        return !_queue.isSuspended
    }
    
    var id:String{
        return _orderID
    }
    
    //暂停任务
    func pause()
    {
        _queue.isSuspended = true
    }
    
    //恢复任务
    func resume()
    {
        _queue.isSuspended = false
    }
    
    private func uploadFail()
    {
        
    }
    
    private func uploadAllComplete()
    {
        NotificationCenter.default.post(name: NotificationName.PageUploadAllComplete, object: nil, userInfo: [SWKey.orderID:_orderID])
    }
    
    private func uploadSuccess(_ response:SWUploadResponse)
    {
        if let index = _pages.index(where: {$0.pageID == response.pageID}),
           let page = _pages.valueAt(index)
        {
            if response.origin
            {
                page.largeResultURL = response.url
            }
            else
            {
                page.previewResultURL = response.url
            }
        }
        let uploadedPagesCount:Int = _record.uploadedPages.count
        let progress:CGFloat = CGFloat(uploadedPagesCount) / CGFloat(_totalCount)
        trace("上传完成:", uploadedPagesCount, progress, _totalCount, response.url)
        
        if uploadedPagesCount >= _totalCount
        {
            uploadAllComplete()
        }
        
        if _queue.operations.count == 0
        {
            NotificationCenter.default.post(name: NotificationName.PageUploadQueueComplete, object: nil, userInfo: [SWKey.orderID:_orderID])
        }
        
        NotificationCenter.default.post(name: NotificationName.PageUploadComplete, object: nil, userInfo: [SWKey.orderID:_orderID])
        NotificationCenter.default.post(name: NotificationName.UploadProgressChanged, object: nil, userInfo: [SWKey.orderID:_orderID, SWKey.progress:progress])
        
    }
    
    
}
